BI.namespace('core');

/**
 * 
 */
BI.core.EventManager = new Class({
	initialize: function (){
		this.clickEvent = null;
    	this.mouseOverEvent = null;
    	this.clickEventStack = [];
		this.mouseOverEventStack = [];
	},
	
	onClick: function(event){
		this.clickEvent = event;
	},
	
	onMouseOver: function(event){
		this.mouseOverEvent = event;
	},
	
	fireEvents: function(){
		// mouse click
		if (this.clickEventStack
				&& this.clickEventStack.length > 0){
			var element = this.clickEventStack.pop();
			element.onClick.apply(element, [this.clickEvent]);
		}
		// mouse over / out handling
		if (this.mouseOverEvent
				&& this.mouseOverEventStack.length > 0){
			
			var lastElement = this.mouseOverEventStack.pop();
			
			for (var i = 0; i < this.mouseOverEventStack.length; i++){
				var element = this.mouseOverEventStack[i].sprite;
				if (element.onMouseOut){
					element.onMouseOut.apply(element, [this.mouseOverEvent]);
					element.isMouseOver = false;
				}
			}
			
			if (lastElement.executeAction){
				if (lastElement.sprite.isMouseOver
						&& lastElement.sprite.onMouseOver){
					lastElement.sprite.onMouseOver.apply(lastElement.sprite, [this.mouseOverEvent]);
				} else if (!lastElement.sprite.isMouseOver
								&& lastElement.sprite.onMouseOut){
					lastElement.sprite.onMouseOut.apply(lastElement.sprite, [this.mouseOverEvent]);
				}
			}
		}
		
		this.clickEvent = null;
		this.mouseOverEvent = null;
		this.clickEventStack = [];
		this.mouseOverEventStack = [];
	},
	
	collectEvents: function(sprite, context){
		if (this.clickEvent
				&& sprite.onClick
				&& sprite.isTouched(this.clickEvent.x, this.clickEvent.y, context)){
			this.clickEventStack.push(sprite);
		}
		
		if (this.mouseOverEvent){
			var spriteTouched = sprite.isTouched(this.mouseOverEvent.x, this.mouseOverEvent.y, context);
			// collect mouse over events
			if ((spriteTouched				// is mouse out?
					&& !sprite.isMouseOver)
					|| (!spriteTouched		// is mouse over?
							&& sprite.isMouseOver)){
				this.mouseOverEventStack.push({sprite:sprite, executeAction: true});
				sprite.isMouseOver = !sprite.isMouseOver;
			} else if (spriteTouched 		// is currently on sprite with mouse over state?
						&& sprite.isMouseOver){
				this.mouseOverEventStack.push({sprite:sprite, executeAction: false});
			}
		}
	}
});


